package hhs.scannerapp;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PictureTakerCropActivity extends ActionBarActivity implements CvCameraViewListener2
{
	private PictureTakerViewTimer mOpenCvCameraView;
	private int touchCount = 0;
	private boolean menuChange = false;
	private int menuChangeNum = 0, duration = 10000;
	TextView startView;
	String shape = "cylinder", textureString, threshString = "binary";
	ImageView cameraButton; 
	
	private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) 
	{
		@Override
		public void onManagerConnected(int status) 
		{
			switch (status) 
			{
				case LoaderCallbackInterface.SUCCESS:
				{
					mOpenCvCameraView.enableView();     
				} 
				break;
				default:
				{
					super.onManagerConnected(status);
				}
			}
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.picture_taker_timer_view); 
		mOpenCvCameraView = (PictureTakerViewTimer) findViewById(R.id.picture_taker_timer_surface_view);
		mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
		mOpenCvCameraView.setCvCameraViewListener(this);
		Log.e("onCreate","before orientation request");
		//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		Log.e("onCreate","after orientation request");
		startView = (TextView)findViewById(R.id.start_textView);	
		cameraButton = (ImageView) findViewById(R.id.camera_button);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.threshold_menu, menu);
		return true;
	} 

	@Override
	public boolean onPrepareOptionsMenu (Menu menu) 
	{
		if(menuChange)
		{
			menu.clear();
			if(menuChangeNum == 1)
			{
				 getMenuInflater().inflate(R.menu.texture_menu, menu);
			}
			else if(menuChangeNum == 2)
			{
				 getMenuInflater().inflate(R.menu.shape_menu, menu);
			}
			else if(menuChangeNum == 3)
			{
				 getMenuInflater().inflate(R.menu.shape_no_texture_menu, menu);
			}
		}
		return true;
	}
	
	public void textureProcess()
	{
		startView.setText(R.string.shape_string);
		startView.setOnTouchListener(new View.OnTouchListener() 
		{
			@Override
			public boolean onTouch(View v, MotionEvent event) 
			{
				if (event.getAction() == MotionEvent.ACTION_DOWN)
				{ 
					touchCount++;
					if(touchCount == 1)
					{
						startView.setText(R.string.rotate_string);
					}
					else if(touchCount == 2)
					{
						startView.setRotation(180);
						startView.setText(R.string.start_string);
					}
					else
					{
						startView.setText(R.string.pict_taking_string);
						menuChange = true;
						menuChangeNum = 0;
						invalidateOptionsMenu(); 
						mOpenCvCameraView.takeTexturePicture(duration);
					}
				}
				return true;
			}
		});
	}
	
	public void noTextureProcess()
	{
		menuChange = true;
		menuChangeNum = 0;
		invalidateOptionsMenu(); 
		mOpenCvCameraView.takeNoTexturePicture();			
	}
	
	public void getDurationDialog()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Change Picture Time");
	
		// Set up the input
		final EditText input = new EditText(this);
		// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
		input.setInputType(InputType.TYPE_CLASS_TEXT);
		builder.setView(input);
	
		// Set up the buttons
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
		{ 
		    @Override
		    public void onClick(DialogInterface dialog, int which) 
		    {
		    	try
				{
		    		 duration = Integer.parseInt(input.getText().toString());
				}
				catch(NumberFormatException e)
				{
					Toast.makeText(getBaseContext(), "Duration Must Be A NUMBER!", Toast.LENGTH_SHORT).show();
				}
		    }
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		        dialog.cancel();
		    }
		});
	
		builder.show();
	}

	@Override
	public void onPause()
	{
		super.onPause();
		if (mOpenCvCameraView != null)
		{
			mOpenCvCameraView.disableView();
			mOpenCvCameraView.releaseCam();
		}
	}

	@Override
	public void onResume()
	{
		super.onResume();
		OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, this, mLoaderCallback);
	}

	public void onDestroy() 
	{
		super.onDestroy();
		if (mOpenCvCameraView != null)
		{
			mOpenCvCameraView.disableView();
			mOpenCvCameraView.releaseCam();
		}
	}

	public void onCameraViewStarted(int width, int height) {}

	public void onCameraViewStopped() 
	{
		if (mOpenCvCameraView != null)
		{
			mOpenCvCameraView.disableView();
			mOpenCvCameraView.releaseCam();
		}
	}

	public Mat onCameraFrame(CvCameraViewFrame inputFrame) 
	{	
		//return inputFrame.rgba();
		return threshold(inputFrame.rgba());
	}

	public Mat threshold(Mat mat)
	{
		int maxValue = 255;
		int minValue = 0;
		Mat tempMat = new Mat();
		Imgproc.cvtColor(mat, tempMat, Imgproc.COLOR_BGR2GRAY);
		Log.e("threshold",threshString);
		if(threshString.equals("light"))
		{
			Log.e("threshold light",threshString);
			Imgproc.threshold(tempMat, mat, minValue, maxValue, Imgproc.THRESH_OTSU);
		}
		else if(threshString.equals("dark"))
		{
			Log.e("threshold dark",threshString);
			Imgproc.threshold(tempMat, mat, minValue, maxValue, Imgproc.THRESH_OTSU);
		}
		return mat;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		switch (item.getItemId()) 
		{ 
			case R.id.with_texture:
				textureString = "texture";
				menuChangeNum = 2;
				menuChange = true;
				invalidateOptionsMenu();
				textureProcess();
				break;
			case R.id.without_texture:
				textureString = "no texture";
				menuChangeNum = 3;
				menuChange = true;
				invalidateOptionsMenu();
				startView.setText(R.string.shape_no_texture_string);
				break;
			case R.id.light_object:
				menuChangeNum = 1;
				menuChange = true;
				invalidateOptionsMenu();
				threshString = "light";
				startView.setText(R.string.texture_string);	
				break;
			case R.id.dark_object:
				menuChangeNum = 1;
				menuChange = true;
				invalidateOptionsMenu();
				threshString = "dark";
				startView.setText(R.string.texture_string);		
				break;
			case R.id.no_text_box:
				shape = "box";
				noTextureProcess();
				break;
			case R.id.no_text_cylinder:
			case R.id.no_text_sphere:
				shape = "cylinder";
				noTextureProcess();
				break;
			case R.id.text_box:
				shape = "box";
				textureProcess();
				break;
			case R.id.text_cylinder:
			case R.id.text_sphere:
				shape = "cylinder";
				textureProcess();
				break;
			case R.id.text_duration:
				getDurationDialog();
				break;
			default:
				break;
		}
		return true;
	}
}
